﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using LetiLib.Data;
using LetiLib.Utils;

namespace LedCenter.GUI
{
    public partial class BusControl : UserControl
    {
        public BusControl()
        {
            InitializeComponent();
            this.numRows.Value = 1;

            this.numColums.Value = 1;
        }

        TABLE_POPUP _popup;

        public TABLE_POPUP DataSource
        {
            get { return _popup; }
            set{
                if (value == null)
                {
                    this.numRows.Value = 1;

                    this.numColums.Value = 1;
                    return;
                }

                _popup = value;
                this.numRows.Value = value.Table.Rows;

                this.numColums.Value = value.Table.Columns;

                TABLE table = value.Table;
                string rawString = table.getRawDataString();
                string[] dataArray = rawString.Split(table.SplitSymbol);

                for (int i = 0; i < table.Rows; i++)
                {
                    for (int j = 0; j < table.Columns; j++)    
                    {
                        NumericUpDown numTemp = (NumericUpDown)this.tableLayoutPanel1.GetControlFromPosition(j+1, i);
                        if (numTemp != null)
                        {
                            string strTemp = dataArray[i * table.Columns + j];
                            double dTemp = 0;
                            try
                            {
                                // check if data is interger
                                dTemp = int.Parse(strTemp);
                                numTemp.DecimalPlaces = 0;
                                numTemp.Increment = 1;
                            }
                            catch (System.Exception ex)
                            {
                                try
                                {
                                    // check if data is double
                                    dTemp = double.Parse(strTemp);
                                    numTemp.DecimalPlaces = 1;
                                    numTemp.Increment = (Decimal)0.1F;
                                }
                                catch (System.Exception ex1)
                                {
                                    Debug.WriteLine("Wrong bus data table!");	
                                }
                            }
                            numTemp.Value = new System.Decimal(dTemp);
                        }
                    }
                }
                this.Invalidate(true);
            }
        }

        public BusControl(TABLE_POPUP p)
        {
            
            InitializeComponent();
            if (p.DataType == POPUP_TYPE.TABLE)
            {
                this.DataSource = p;
            }
            
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            // Table ContentData
            //POPUP pTable = DataSource;

            // Get content data from TABLE
            string content = getContentData(_popup.Table);

            _popup.Table.ContentData = content;

            if (BusUpdate != null)
                BusUpdate();
        }

        public delegate void BusUpdateHandler();
        public event BusUpdateHandler BusUpdate;

        #region | System control |
        public delegate void GetBrightHandler();
        public event GetBrightHandler OnGetBright;
        private void btnGetBright_Click(object sender, EventArgs e)
        {
            if (OnGetBright != null)
                OnGetBright();
        }

        public delegate void GetVersionHandler();
        public event GetVersionHandler OnGetVersion;
        private void btnGetFirmware_Click(object sender, EventArgs e)
        {
            if (OnGetVersion != null)
                OnGetVersion();
        }

        public delegate void GetStatusHandler();
        public event GetStatusHandler OnGetStatus;
        private void btnCheckLed_Click(object sender, EventArgs e)
        {
            if (OnGetStatus != null)
                OnGetStatus();
        }

        public delegate void GetTimeHandler();
        public event GetTimeHandler OnGetTime;
        private void btnSettime_Click(object sender, EventArgs e)
        {

        }

        public delegate void GetActivePageHandler();
        public event GetActivePageHandler OnGetActivePage;
        private void btnGetActivePage_Click(object sender, EventArgs e)
        {
            if (OnGetActivePage != null)
                OnGetActivePage();
        }

        public delegate void GetPageInfoHandler(ushort pageID);
        public event GetPageInfoHandler OnGetPageInfo;
        private void btnGetPageInfo_Click(object sender, EventArgs e)
        {
            ushort pageID = 0;
            string input = Microsoft.VisualBasic.Interaction.InputBox("Choose page ID", "Page chooser", "1");
            try
            {
                pageID = ushort.Parse(input);
                if (OnGetPageInfo != null)
                    OnGetPageInfo(pageID);
            }
            catch (System.Exception ex)
            {

            }

        }

        public delegate void GetImageListHandler();
        public event GetImageListHandler OnGetImageList;
        private void btnGetImageList_Click(object sender, EventArgs e)
        {
            if (OnGetImageList != null)
            {
                OnGetImageList();
            }
        }

        public delegate void ScreenCaptureHandler();
        public event ScreenCaptureHandler OnScreenCapture;
        private void btnCapture_Click(object sender, EventArgs e)
        {
            if (OnScreenCapture != null)
            {
                OnScreenCapture();
            }
        }

        #endregion

        /// <summary>
        /// Update tablelayout based on new rows and columns
        /// </summary>
        /// <event> Called when row and columns changed </event>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private void numColumns_ValueChanged(object sender, EventArgs e)
        {
            // Suspend GUI logic for updating table rows and columns
            this.SuspendLayout();
             
            // get new rows and columns 

            uint row = (uint)numRows.Value;     // rows
            uint column = (uint)numColums.Value;// columns

            // Update table layout
            tableLayoutPanel1.ReInitTable(column, row);

            // Table ContentData
            TABLE table = DataSource.Table;
            _popup.Table.Rows = (byte)row;
            _popup.Table.Columns = (byte)column;

            // Get content data from TABLE
            string content = getContentData(_popup.Table);

            Debug.WriteLine(content);
            _popup.Table.ContentData = content;
            // Resume normal GUI logic
            this.ResumeLayout();
            //Invalidate();
        }

        private string getContentData(TABLE table)
        {
            //if (table)
            // Get content data from controls
            color = "#g"; oldColor = "";
            StringBuilder bufString = new StringBuilder();
            for (int i = 0; i < table.Rows; i++)
            {
                for (int j = 0; j < table.Columns; j++)
                {
                    NumericUpDown numTemp = (NumericUpDown)this.tableLayoutPanel1.GetControlFromPosition(j + 1, i);
                    if (numTemp != null)
                    {
                        //numTemp.Value = new System.Decimal(dTemp);
                        bufString.Append(getStringFromValue((double)numTemp.Value));
                    }
                    else
                    {
                        bufString.Append(getStringFromValue(0));
                    }
                }
            }
            return bufString.Length > 1 ? bufString.ToString().Substring(0, bufString.Length - 1) : bufString.ToString();
        }
        private string color = "#g", oldColor = "";
        private string getStringFromValue(double val)
        {
            string outString;
            if (val < 0.5)
                color = EnumUtils.GetEnumDescription(HASH_TAG.COLOR_RED);
            else if (val >= 0.5 && val < 0.9)
                color = EnumUtils.GetEnumDescription(HASH_TAG.COLOR_YELLOW);
            else if (val > 1 )
                color = EnumUtils.GetEnumDescription(HASH_TAG.COLOR_GREEN);

            if (color == oldColor)
                outString = String.Format("{0:0.0};", val);
            else
                outString = String.Format("{0}{1:0.0};", color, val);

            oldColor = color;

            return outString;
        }
        private void BusControl_VisibleChanged(object sender, EventArgs e)
        {
            foreach(Control c in Controls)
            {
                c.Visible = this.Visible;
            }
        }
    }
}
